// 续费预警
<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
      label-width="100px"
    >
      <el-form-item label="搜索学员" prop="wxParam">
        <el-input
          v-model="queryParams.wxParam"
          placeholder="请输入学员姓名/手机号"
          clearable
          style="width: 240px"
          @keyup.enter="getList"
        >
          <template #append>
            <el-button :icon="Search" @click="getList" />
          </template>
        </el-input>
      </el-form-item>

      <el-form-item label="报读课程" prop="courseId">
        <el-select
          v-model="queryParams.courseId"
          placeholder="请选择报读课程"
          clearable
          style="width: 240px"
        >
          <el-option
            v-for="item in courseList"
            :key="item.id"
            :label="item.state === '1' ? item.name + '(已停用)' : item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="班级老师" prop="teacherId">
        <el-select
          v-model="queryParams.teacherId"
          placeholder="请选择班级老师"
          clearable
          style="width: 240px"
        >
          <el-option
            v-for="item in teacherList"
            :key="item.value"
            :label="
              !item.isJob
                ? item.label + '(已离职)'
                : !item.isTeacher
                ? item.label + '(非授课)'
                : item.label
            "
            :value="item.value"
          />
        </el-select>
      </el-form-item> -->
      <!-- <el-form-item label="所在班级" prop="classId">
        <el-select
          v-model="queryParams.classId"
          placeholder="请选择所在班级"
          clearable
          style="width: 240px"
        >
          <el-option
            v-for="item in classList"
            :key="item.id"
            :label="item.beOver === '0' ? item.name + '(已结业)' : item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item> -->

      <el-form-item label="跟进人" prop="counselorId">
        <el-select
          v-model="queryParams.counselorId"
          placeholder="请选择跟进人"
          clearable
          style="width: 240px"
        >
          <el-option
            v-for="item in counselors"
            :key="item.id"
            :label="item.nickName"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="学管师" prop="managementId">
        <el-select
          v-model="queryParams.managementId"
          placeholder="请选择学管师"
          clearable
          style="width: 240px"
        >
          <el-option
            v-for="item in managerArr"
            :key="item.id"
            :label="item.nickName"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="是否超上" prop="overClass">
        <div style="width: 240px">
          <el-checkbox
            v-model="queryParams.overClass"
            label="有超上"
            true-value="1"
            false-value=""
            @change="handleQuery"
          />
        </div>
      </el-form-item>

      <el-form-item label="是否停课" prop="stopsResume">
        <div style="width: 80px">
          <el-checkbox
            v-model="queryParams.stopsResume"
            label="未停课"
            true-value="1"
            false-value=""
            @change="handleQuery"
          />
        </div>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          @click="handleSet"
          v-hasPermi="['sales:renewalAlert:setting']"
          >预警设置</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button type="plain" plain icon="Download" @click="handleExport"
          >导出</el-button
        >
      </el-col>

      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList">
      </right-toolbar>
    </el-row>
    <el-alert
      type="warning"
      :closable="false"
      style="font-size: 14px; color: #666"
      v-if="form.id"
    >
      <template v-slot:title>
        <span>
          预警值： 剩余课时≤{{ form.remainingClass }}课时
          {{ form.type === "1" ? "或" : "且" }} 剩余天数≤{{
            form.remainingDay
          }}天
        </span>
        <span style="margin-left: 20px">
          排序规则：默认按剩余生效课次数从小到大, 超上的课次按从大到小
        </span>
        <br />
        <span
          >续费提醒：仅可对已开启通知用户发送续费提醒，且提醒数（/用户/日）<=
          1次</span
        >
      </template>
    </el-alert>
    <el-table v-loading="loading" :data="list" border>
      <el-table-column
        label="学员名称"
        align="center"
        prop="name"
        :show-overflow-tooltip="true"
        fixed="left"
      >
        <template #default="scope">
          <router-link
            :to="'/registrar/studentsDetails/detail/' + scope.row.id"
            class="link-type"
          >
            <span>{{ scope.row.name }}</span>
          </router-link>
        </template>
      </el-table-column>
      <el-table-column label="手机号" align="center" prop="mobile" width="160">
        <template #default="scope">
          {{ scope.row.mobile }}
          <el-tooltip
            class="box-item"
            effect="dark"
            content="已绑定小程序"
            placement="top"
            v-if="scope.row.openid"
          >
            <img src="@/assets/images/mini-pro.svg" width="14" />
          </el-tooltip>
          <el-tooltip
            class="box-item"
            effect="dark"
            content="未绑定小程序"
            placement="top"
            v-else
          >
            <img src="@/assets/images/no-mini-pro.svg" width="14" />
          </el-tooltip>
          <el-tooltip
            class="box-item"
            effect="dark"
            content="已开启通知"
            placement="top"
            v-if="scope.row.mpid"
          >
            <img
              src="@/assets/images/notice.svg"
              width="14"
              style="margin: 0 5px"
            />
          </el-tooltip>
          <el-tooltip
            class="box-item"
            effect="dark"
            content="未开启通知"
            placement="top"
            v-else
          >
            <img
              src="@/assets/images/no-notice.svg"
              width="14"
              style="margin: 0 5px"
            />
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column label="课程名称" align="center" prop="courseName" />
      <el-table-column
        label="订单编号"
        align="center"
        prop="orderNo"
        min-width="140"
      />
      <!-- <el-table-column label="所在班级" align="center" prop="className" /> -->
      <el-table-column label="授课方式" align="center" prop="lessonType">
      </el-table-column>
      <el-table-column label="剩余数量" align="center" prop="remainderLesson" />
      <el-table-column
        label="到期日期"
        align="center"
        prop="expireDate"
        min-width="140"
      >
        <template #default="scope">
          {{ scope.row.expireDate && scope.row.expireDate.slice(0, 10) }}
        </template>
      </el-table-column>
      <!-- <el-table-column label="班级老师" align="center" prop="teacherName" /> -->
      <el-table-column label="跟进人" align="center" prop="counselorName" />
      <el-table-column label="学管师" align="center" prop="managementName" />
      <el-table-column
        label="上次提醒时间"
        align="center"
        prop="renewalReminderTime"
        min-width="140"
      />
      <el-table-column
        label="操作"
        align="center"
        width="160"
        class-name="small-padding fixed-width"
        fixed="right"
      >
        <template #default="scope">
          <router-link
            :to="'/registrar/studentsSignUp/index/' + scope.row.studentId"
            class="link-type"
          >
            <el-button
              link
              type="primary"
              v-hasPermi="['financial:order:option']"
            >
              续费
            </el-button>
          </router-link>
          <el-button
            link
            type="primary"
            @click="handleAlert(scope.row)"
            v-hasPermi="['financial:order:option']"
            :disabled="scope.row.sendType === 0"
          >
            续费提醒
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <el-dialog v-model="openSetting" title="预警设置" width="500">
      <div class="content">
        <div class="tip">满足以下条件的学员将进入续费预警列表：</div>
        <el-radio-group v-model="form.type">
          <el-radio value="1">
            剩余课时 ≤
            <el-input
              v-model="form.remainingClass"
              style="width: 90px; margin: 0px 8px"
              @input="
                (value) =>
                  (form.remainingClass = Number(value.replace(/[^\d]/g, '')))
              "
            />
            或 剩余天数 ≤
            <el-input
              v-model="form.remainingDay"
              style="width: 90px; margin: 0px 8px"
              @input="
                (value) =>
                  (form.remainingDay = Number(value.replace(/[^\d]/g, '')))
              "
            />
          </el-radio>
          <el-radio value="2">
            剩余课时 ≤
            <el-input
              v-model="form.remainingClass"
              style="width: 90px; margin: 0px 8px"
              @input="
                (value) =>
                  (form.remainingClass = Number(value.replace(/[^\d]/g, '')))
              "
            />
            且 剩余天数 ≤
            <el-input
              v-model="form.remainingDay"
              style="width: 90px; margin: 0px 8px"
              @input="
                (value) =>
                  (form.remainingDay = Number(value.replace(/[^\d]/g, '')))
              "
            />
          </el-radio>
        </el-radio-group>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancelSettings()">取消</el-button>
          <el-button type="primary" @click="saveSettings()"> 保存 </el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog v-model="openAlert" title="续费提醒" width="500">
      <div class="content">
        <el-alert
          title="续费提醒将通过微信推送的形式发送给家长"
          type="warning"
          show-icon
          :closable="false"
        />
        <el-form label-width="100px">
          <el-row>
            <el-col :span="24">
              <el-form-item label="接收人：">
                {{ currentItem.name }}
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="推送内容：">
                <el-form label-width="90px">
                  <el-row>
                    <el-col :span="24">
                      <el-form-item label="学生姓名：">
                        {{ currentItem.name }}
                      </el-form-item>
                    </el-col>
                    <el-col :span="24">
                      <el-form-item label="课程名称：">
                        {{ currentItem.courseName }}
                      </el-form-item>
                    </el-col>
                    <el-col :span="24">
                      <el-form-item label="内容类型：">
                        续费提醒
                        {{
                          currentItem.expireDate
                            ? "(" +
                              currentItem.courseName +
                              "   到期时间" +
                              currentItem.expireDate.slice(0, 10) +
                              ")"
                            : ""
                        }}
                      </el-form-item>
                    </el-col>
                  </el-row>
                </el-form>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancelAlert()">取消</el-button>
          <el-button type="primary" @click="sendAlert()"> 发送 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="RenewalAlert">
import { Search } from "@element-plus/icons-vue";
import {
  getAlertListAPI,
  saveSettingsAPI,
  getSettingsAPI,
  exportListAPI,
  setMessageAPI,
  toNoticeAPI,
} from "@/api/salesCenter/renewalAlert";
import { getCourseListAPI } from "@/api/registrar/course";
import {
  getFollowPeopleList,
  getManagerList,
  getPeopleList,
} from "@/api/studentManagement/index.js";

import { getClassListAPI } from "@/api/registrar/class";

const { proxy } = getCurrentInstance();
const loading = ref(false);
const showSearch = ref(true);
const total = ref(0);

const list = ref([]);
//const teacherList = ref([]);
const courseList = ref([]); // 课程列表
//const classList = ref([]); // 班级列表
const counselors = ref([]); // 跟进人列表
const managerArr = ref([]); // 学管师列表
const currentItem = ref({});
const openSetting = ref(false);
const openAlert = ref(false);
const data = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    wxParam: "", // 姓名或手机号
    courseId: null, // 课程
    //teacherId: null,
    //classId: null,
    stopsResume: "1", // 是否停课，0是1否
    overClass: "0", // 是否有超上，1是0否
    counselorId: null, // 跟进人
    managementId: null, // 学管师
  },
  form: {
    id: null,
    remainingClass: 0,
    remainingDay: 0,
    type: "1",
  },
});

const { queryParams, form } = toRefs(data);

// 方法-------------------------------------------------------------------------------------------------------------

// 获取跟进人
const getFollowPeople = async () => {
  counselors.value = [];
  const { rows } = await getFollowPeopleList({ pageNum: 1, pageSize: 9999 });
  counselors.value = rows;
};

// 获取学管师
const getManagerDatas = async () => {
  managerArr.value = [];
  const { data } = await getManagerList({ pageNum: 1, pageSize: 9999 });
  managerArr.value = data;
};

// 获取教师列表
function getTeacherList() {
  loading.value = true;
  getPeopleList({ isTeach: 1 }).then((response) => {
    teacherList.value = response.data;
    loading.value = false;
  });
}

// 班级
function getClassList() {
  loading.value = true;
  getClassListAPI({ pageSize: 9999, pageNum: 1 }).then((response) => {
    classList.value = response.rows;
    loading.value = false;
  });
}

function getList() {
  loading.value = true;
  getAlertListAPI(
    { ...queryParams.value, type: form.value.type }
    //proxy.addDateRange(queryParams.value, {  })
  ).then((response) => {
    list.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 获取关联课程
function getCourseList() {
  getCourseListAPI({ pageSize: 9999, pageNum: 1 }).then((response) => {
    courseList.value = response.rows;
    loading.value = false;
  });
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 导出
function handleExport() {
  let {
    wxParam,
    courseId,
    // teacherId,
    //classId,
    stopsResume,
    overClass,
    counselorId,
    managementId,
  } = queryParams.value;
  exportListAPI({
    wxParam,
    courseId,
    //teacherId,
    //classId,
    stopsResume,
    overClass,
    counselorId,
    managementId,
    type: form.value.type,
  }).then((res) => {
    let blob = new Blob([res], {
      type: "application/vnd.ms-excel;charset=utf-8",
    });
    const url = window.URL.createObjectURL(blob),
      link = document.createElement("a"); // 创建a标签
    link.href = url;
    link.download = "续费预警列表";
    link.click();
    URL.revokeObjectURL(url); // 释放内存
    proxy.$modal.msgSuccess("导出成功");
  });
}

function saveSettings() {
  loading.value = true;
  const { id, remainingClass, remainingDay, type } = form.value;
  saveSettingsAPI({
    id,
    remainingClass,
    remainingDay,
    type,
  }).then(() => {
    loading.value = false;
    openSetting.value = false;
    getSettings();
  });
}

function getSettings() {
  loading.value = true;
  getSettingsAPI().then((res) => {
    loading.value = false;
    if (res.data) form.value = res.data;
    1;
    handleQuery();
  });
}

function cancelSettings() {
  //classTypeForm.value.copyClassTypeList = [...classTypeList.value];
  openSetting.value = false;
}

// 预警设置
function handleSet() {
  openSetting.value = true;
  //getSettings();
}

// 续费提醒
function handleAlert(row) {
  currentItem.value = row;
  openAlert.value = true;
}

// 取消续费提醒
function cancelAlert() {
  openAlert.value = false;
}

// 发送续费提醒
function sendAlert() {
  // 调用发送方法
  //proxy.$modal.msgError("调用发送方法还未实现，敬请期待");
  openAlert.value = false;
  let content =
    "续费提醒" +
    (currentItem.value.expireDate
      ? "(" +
        currentItem.value.courseName +
        "  到期时间" +
        currentItem.value.expireDate.slice(0, 10) +
        ")"
      : "");

  setMessageAPI({
    content,
    toId: currentItem.value.studentId,
    orderId: currentItem.value.orderId,
  }).then((res) => {
    proxy.$modal.msgSuccess("发送成功");
    loading.value = false;
    openAlert.value = false;
    if (res.data.ids) toNotice(res.data.ids);
    setTimeout(() => {
      handleQuery();
    }, 1000);
  });
}

function toNotice(ids) {
  toNoticeAPI({
    ids,
  });
}

//调用---------------------------------------------------------------------------------------------------------------
getCourseList();
getFollowPeople(); // 获取跟进人
getManagerDatas(); // 获取学管师
//getTeacherList();
//getClassList();
getSettings();
</script>
<style scoped lang="scss">
.tip {
  color: black;
  line-height: 20px;
  margin-bottom: 16px;
  font-size: 14px;
}

:deep .el-radio__input.is-checked + .el-radio__label {
  color: rgb(96, 98, 102);
}

.el-radio {
  margin-bottom: 12px;
}
</style>
